import axios from 'axios'
import { getToken } from '@/utils/cookie'
import { showMessage } from '@/composables/util'

// 创建Axios
const instance = axios.create({
  baseURL: '/api',
  timeout: 7000
})

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    let errorMessage = error.response.data.message || '请求失败'
    showMessage(errorMessage, 'error')
    return Promise.reject(error)
  }
)

export default instance
